package inet.app.vod.activity.news;

import inet.app.vod.activity.R;
import inet.app.vod.activity.common.BaseActivity;
import inet.app.vod.config.AppConstants;
import inet.app.vod.db.DaoFactory;
import inet.app.vod.db.DaoNew;
import inet.app.vod.net.http.VolleyClient;
import inet.app.vod.net.http.VolleyListener;
import inet.app.vod.object.NewModel;
import inet.app.vod.object.ResultJsonModel;
import inet.app.vod.parser.Parse;
import inet.app.vod.util.MyUtil;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.inet.app.framework.device.DeviceUtil;
import com.inet.app.framework.util.Log;
import com.inet.app.framework.widget.MyToast;

public class INewsDetailActivity extends BaseActivity {

	public final static String TEXT_COLOR = "white";
	public final static int TEXT_SIZE = 4;

	private NewModel mNew;
	private DaoNew mDaoNew;

	private View.OnClickListener shareListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			shareItem("iNews", mNew.getFbLink(), mNew.getTitle(), mNew.getImg());
		}
	};

	private void initModels() {
		mDaoNew = DaoFactory.getInstance(getApplicationContext()).getDaoNew();
		Bundle bundle = getIntent().getExtras();
		if (null != bundle) {
			mNew = (NewModel) bundle.getSerializable("item_new");
		}
		if (mNew == null) {
			MyToast.show(this, "Không có bài viết này");
			finish();
			return;
		}

	}

	private void initViews() {
		setTitle(getResources().getString(R.string.inews));
		findViewById(R.id.share_button).setOnClickListener(shareListener);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_inews_detail);
		initUIBase();
		initModels();
		initViews();
		requestDetail();
	}

	private void requestDetail() {
		NewModel news = mDaoNew.selectRow(mNew.getId());
		if (news != null) {
			mNew = news;
			Log.d("load new from database");
			showNew();
		} else {
			VolleyClient.requestDetails(AppConstants.ID_INEWS, mNew.getId(),
					new VolleyListener(this) {

						@Override
						public void onSuccess(String response) {
							ResultJsonModel jResult = Parse
									.parseNewDetail(response);
							if (jResult == null) {
								// error parser
								MyUtil.showDialog(
										"Không thể lấy nội dung bài viết",
										INewsDetailActivity.this);
							} else if (jResult.hasError()) {
								// error register
								String error = jResult.getError();
								MyUtil.showDialog(error,
										INewsDetailActivity.this);
							} else {
								// save categories to database
								String content = (String) jResult.getResult();
								mNew.setContent(content);
								saveNewToDB();
								Log.d("load new from network");
								showNew();
							}
						}

						@Override
						public void onStart() {
							showLoading(true);
						}

						@Override
						public void onFinish() {
							showLoading(false);
						}

						@Override
						public void onError(VolleyError error) {
							MyUtil.showDialog(
									"Lỗi tải bài viết (" + error.getMessage()
											+ ")", INewsDetailActivity.this);
						}
					});
		}
	}

	private void saveNewToDB() {
		mDaoNew.insertRow(mNew);
	}

	private void showNew() {

		TextView title = (TextView) findViewById(R.id.title_text);
		title.setText(mNew.getTitle());

		String content = mNew.getContent();
		// change background and text color
		content = new StringBuffer("<font color=\"").append(TEXT_COLOR)
				.append("\"").append(" size=\"").append(TEXT_SIZE)
				.append("\">").append(content).append("</font>").toString();
		WebView webContent = (WebView) findViewById(R.id.content_webview);
		if (TextUtils.isEmpty(content)) {
			webContent.setVisibility(View.GONE);
			return;
		}

		String mime = "text/html";
		String encoding = "utf-8";
		webContent.setBackgroundColor(getResources().getColor(
				R.color.black_background));
		webContent.getSettings().setJavaScriptEnabled(true);

		// change size of tag images
		String imgRegex = "<IMG[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>";
		Pattern pattern = Pattern.compile(imgRegex);
		Matcher matcher = pattern.matcher(mNew.getContent());
		int widthDevice = DeviceUtil.getSimpleDeviceInfo(this).getWidth();
		StringBuffer tagImg;
		String oldTag;
		while (matcher.find()) {
			oldTag = matcher.group();
			tagImg = new StringBuffer(oldTag);
			int len = tagImg.length();
			tagImg.deleteCharAt(len - 1)
					.append(" width=\"" + (widthDevice / 2) + "\"").append(">");
			content = content.replace(oldTag, tagImg.toString());
		}
		webContent.loadDataWithBaseURL(null, content, mime, encoding, null);
	}

	@Override
	public void setTagMenu() {
		mTagMenu = AppConstants.MENU_INEWS;
	}

}
